<template>
  <a-tooltip :content="text" v-if="isOverflow">
    <div class="overflow-text" ref="textElement" :style="{maxWidth: maxWidth}" :title="text">
      {{ text }}
    </div>
  </a-tooltip>
  <div v-else class="overflow-text" ref="textElement" :style="{maxWidth: maxWidth}">
    {{ text }}
  </div>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      required: true
    },
    // 默认最大宽度为 100%
    maxWidth: {
      type: String,
      default: '100%' // 根据父容器的宽度来设置
    }
  },
  data () {
    return {
      isOverflow: false
    }
  },
  mounted () {
    this.checkOverflow()
  },
  updated () {
    this.checkOverflow()
  },
  methods: {
    checkOverflow () {
      const element = this.$refs.textElement
      this.isOverflow = element.scrollWidth > element.clientWidth
    }
  }
}
</script>

<style scoped>
.overflow-text {
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden;
  text-overflow: ellipsis;
  /* font-size: 14px; */
  /* color: #333; */
}
</style>
